﻿#include <QFileDialog>
#include <QMessageBox>
#include <QHBoxLayout>
#include <QStyle>

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "WidgetUtils.h"
#include "CommunicationManager.h"
#include "DeviceManager.h"
#include "BaseLiquidSensor.h"
#include "XKCLiquidSensor.h"
#include "GlobalVar.h"
#include "widgetutils.h"
#include "FileUtils.h"
#include "QProcessPro.h"
#include "logger.h"
#include "DialogStyle.h"
#include "DialogConfig.h"
#include "ControllerManager.h"
#include "GlobalEnum.h"
#include "WaitUtils.h"
#include "NotificationManager.h"
#include "SingleMeasureController.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(&Logger::Instance(),SIGNAL(OnLogging(QString)),this,SLOT(Log(QString)));
    startTimer(3000);

    qRegisterMetaType<DeviceStateItems>("DeviceStateItems");
    qRegisterMetaType<RunModeZZZ>("RunModeZZZ");
    qRegisterMetaType<ControlTypeZZZ>("ControlTypeZZZ");

    WidgetUtils::Execute(this,[this]()
    {
        //创建托盘
        trayIcon = CreateTrayIcon(this->windowTitle());
        trayIcon->show();

        CommunicationManager::Instance().InitConfig();
        CommunicationManager::Instance().SetEnableMonitor(true);

        DeviceManager &mgr=DeviceManager::Instance();
        mgr.Register<BaseLiquidSensor>();
        mgr.Register<XKCLiquidSensor>();
        mgr.InitConfig();
        mgr.SetMonitorInterval(2);
        mgr.SetEnableDeviceMonitor(true);
        connect(&mgr,&DeviceManager::StateUpdated,this,&MainWindow::OnStateUpdateHandle);

        ControllerManager &cmgr=ControllerManager::Instance();
        cmgr.Register<SingleMeasureController>();
        ControllerManager::Instance().SetGetMeasureModeFunc([this]{
            return "AutoSample";
        });
        cmgr.InitConfig();
        BaseController *controller=cmgr.GetController("AutoSample");
        ui->cmbAllCmd->clear();
        ui->cmbAllCmd->addItems(controller->GetCommandNames());

        _ioModule=mgr.GetItem<BaseIOModule>("IOModule");
        this->setWindowFlag(Qt::WindowMinMaxButtonsHint);

        connect(&NotificationManager::Instance(),&NotificationManager::OnReport,this,&MainWindow::OnHandleInstrumentStatusChanged);

        QStringList arrTakeSample={"取样阀","取样蠕动泵","水阀"};
        InitGroupBox(arrTakeSample,ui->gbTakeSample);

        QStringList arrInSample={"浮球液位传感器","吸附液位传感器","自动进样夹管阀","手动进样夹管阀","进样蠕动泵"};
        InitGroupBox(arrInSample,ui->gbInSample);

        QStringList arrBlow={"水平吹扫","环形吹扫"};
        InitGroupBox(arrBlow,ui->gbBlow);

        QStringList arrBack={"出口夹管阀"};
        InitGroupBox(arrBack,ui->gbBack);
    });
    ui->btnStart->setProperty("flag","control");
    ui->btnStop->setProperty("flag","control");
    ui->btnReset->setProperty("flag","control");
    ui->btnRunSingle->setProperty("flag","control");

    UpdateStyle();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::InitGroupBox(QStringList labels,QGroupBox* gb)
{
    for(QString item:labels)
    {
        AddIOLabel(item,gb);
    }
    auto parentLayout=dynamic_cast<QVBoxLayout*>(gb->layout());
    parentLayout->addItem(new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding));
}

void MainWindow::AddIOLabel(QString label,QGroupBox* parent)
{
    QHBoxLayout* layout = new QHBoxLayout();
    layout->setSpacing(10);
    QLabel* wlab = new QLabel(parent);
    QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    sizePolicy.setHorizontalStretch(1);
    sizePolicy.setVerticalStretch(1);
    sizePolicy.setHeightForWidth(wlab->sizePolicy().hasHeightForWidth());
    wlab->setSizePolicy(sizePolicy);

    int size=20;
    wlab->setMinimumSize(QSize(size, size));
    wlab->setMaximumSize(QSize(size, size));
    wlab->setText("");
//    if(label=="液位传感器")
//    {
//        wlab->setText("10.00");
//        wlab->setProperty("state","num");
//    }
//    else
//    {
//        wlab->setProperty("state","off");
//    }

    wlab->setProperty("state","off");
    _deviceMap.insert(label,wlab);
    layout->addWidget(wlab);

    QLabel* lblTxt = new QLabel(parent);
    lblTxt->setProperty("flag","device");
    lblTxt->setText(label);
    layout->addWidget(lblTxt);
    auto parentLayout=dynamic_cast<QVBoxLayout*>(parent->layout());
    parentLayout->addLayout(layout);

}

void MainWindow::OnStateUpdateHandle(DeviceStateItems items)
{
    QElapsedTimer t;
    t.start();
    for(int i=0;i<items.count();i++)
    {
        DeviceStateItem item=items.at(i);
        QString dt=item.DataType;
        if(_deviceMap.contains(item.DataType))
        {
//            qDebug()<<__FUNCTION__<<__LINE__<<dt<<item.Data;
//            if(dt=="液位传感器")
//            {
//                _deviceMap[dt]->setText(item.Data);
//            }
//            else
//            {
//                QString state=item.Data.trimmed()=="0"?"off":"on";
//                _deviceMap[dt]->setProperty("state",state);
//            }

            QString state=item.Data.trimmed()=="0"?"off":"on";
            _deviceMap[dt]->setProperty("state",state);

            QWidget *widget=_deviceMap[dt];
            widget->style()->unpolish(widget);
            widget->style()->polish(widget);
        }
    }
//    qDebug()<<__FUNCTION__<<__LINE__<<t.elapsed()<<"ms";
}


void MainWindow::Log(QString log)
{
    ui->txtLog->appendPlainText(log);
    if(ui->txtLog->document()->lineCount()>500)
    {
        ui->txtLog->document()->clear();
    }
}


void MainWindow::on_btnStart_clicked()
{
    OnHandleInstrumentStatusChanged("",0);
    ControllerManager::Instance().OnPanelHandle(ControlTypeZZZ::StartMeasure);
}

void MainWindow::on_btnStopColl_clicked()
{
    _interrupter.Stop();
}

void MainWindow::on_btnOpenDir_clicked()
{
//    QString folderPath = QFileDialog::getExistingDirectory(this, "选择文件夹", QCoreApplication::applicationDirPath());
//    if(!folderPath.isEmpty())
//    {
//        ui->lineEdit->setText(folderPath);
//    }
}

QString MainWindow::ReadAll(QProcess &process)
{
    if(process.canReadLine())
    {
        QByteArray qba =process.readAll();
        QTextCodec* pTextCodec = QTextCodec::codecForName("System");
        QString str = pTextCodec->toUnicode(qba);
        return str;
    }
    return "";
}

void MainWindow::on_btnOpenFile_clicked()
{
//    QString folderPath = QFileDialog::getOpenFileName(this, "选择文件", QCoreApplication::applicationDirPath());
//    if(!folderPath.isEmpty())
//    {
//        ui->txtInpitFile->setText(folderPath);
//    }
}


QMap<QString,double> MainWindow::GetValue(QString input)
{
    QMap<QString,double> ret;
    if(input.split("\n").count()>4)
    {
        QString lastLine=input.split("\n").at(3).simplified();
        qDebug()<<__FUNCTION__<<__LINE__<<input.split("\n");
        QStringList kv=lastLine.split(" ");
        for(int i=0;i<kv.count();i++)
        {
            QString tv=kv.at(i);
            if(tv.contains("="))
            {
                QString key=tv.split("=").first();
                QString val=tv.split("=").last();
                double dv=val.toDouble();
                ret.insert(key,dv);
            }
        }
    }
    return ret;
}


void MainWindow::on_actionUpdateLog_triggered()
{
    // 创建一个QProcess实例
    static QProcess process;
    // 设置要执行的程序和文件路径作为参数
    process.start("notepad.exe", QStringList() << "./log.ini");
    // 等待进程完成
    process.waitForFinished();
}

void MainWindow::on_actionConfigFile_triggered()
{
    // 创建QProcess对象
    static QProcess process;
    // 设置要启动的程序及其参数
    QString notepadPath = "C:\\Windows\\System32\\explorer.exe";
    QString filePath = ".\\Config";
    QStringList arguments;
    arguments << filePath;
    process.setProgram(notepadPath);
    process.setArguments(arguments);
    // 启动进程
    process.start();
}


void MainWindow::on_actionSetStyle_triggered()
{
    DialogStyle d;
    d.exec();
}

void MainWindow::on_actionIOModule_triggered()
{
    if(_motorW==nullptr)
    {
        BaseItem *motor=DeviceManager::Instance().GetItem<BaseItem>("IOModule");
        _motorW=dynamic_cast<QDialog*>(motor->GetConfigWidget());
        _motorW->setWindowTitle("IO模块调试");
        UpdateStyle();
    }
    _motorW->show();
}

QSystemTrayIcon* MainWindow::CreateTrayIcon(QString title)
{
    QMenu *trayIconMenu=new QMenu(this);
    QAction *quitAction = new QAction("退出", this);
    quitAction->setIcon(QIcon(":/icon/6035_exit_icon.ico"));
    connect(quitAction, &QAction::triggered, this, &MainWindow::CloseWindow);
    trayIconMenu->addAction(quitAction);

    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setContextMenu(trayIconMenu);
    trayIcon->setIcon(QIcon(":/icon/电瓶电解液-1种尺寸.ico"));
    trayIcon->setToolTip(title);

    connect(trayIcon,&QSystemTrayIcon::activated,this,[this](QSystemTrayIcon::ActivationReason reason){
        if(reason==QSystemTrayIcon::DoubleClick)
        {
            this->showNormal();
        }
    });
    return trayIcon;
}

void MainWindow::CloseWindow()
{
    if(trayIcon)
    {
        trayIcon->setVisible(false);
    }
    DeviceManager::Instance().WaitForEnd();
    qDebug()<<__FUNCTION__<<__LINE__<<"DeviceManager End";
    CommunicationManager::Instance().WaitForEnd();
    qDebug()<<__FUNCTION__<<__LINE__<<"CommunicationManager End";
    this->close();
    qApp->quit();
    qDebug()<<"程序关闭！";
}

void MainWindow::UpdateStyle()
{
    QElapsedTimer t;
    t.start();
    QFile qssFile("./Config/ServerStyle.css");
    qssFile.open(QFile::ReadOnly);
    QString ss=qssFile.readAll();
    this->setStyleSheet(ss);
    qApp->setStyleSheet(ss);
    qssFile.close();
    qDebug()<<__FUNCTION__<<__LINE__<<t.elapsed()<<"ms";
}

void MainWindow::timerEvent(QTimerEvent *event)
{
//    UpdateStyle();
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (trayIcon->isVisible())
    {
        QIcon icon(":/Config/gslogo.ico");
        trayIcon->showMessage("提示", "程序仍在后台运行！",icon,1000);
        hide();
        event->ignore();
    }
}

void MainWindow::on_actionConfig_triggered()
{
    DialogConfig d;
    d.exec();
}

void MainWindow::on_btnStop_clicked()
{
    WaitUtils::Stop();
}

void MainWindow::OnHandleInstrumentStatusChanged(QString title,int progress)
{
//    ui->lblMeasureProgress->setText(title);
    ui->progressBar->setValue(progress);
}

void MainWindow::on_btnRunSingle_clicked()
{
    UpdateStyle();
}

void MainWindow::on_actionLiquid_triggered()
{
    QWidget* w=DeviceManager::Instance().GetItem<BaseLiquidSensor>("LiquidSensor")->GetConfigWidget();
    w->setWindowTitle("吸附液位传感器");
    w->show();
    connect(w,&QWidget::destroyed,w,&QWidget::deleteLater);
}
